import React, { useState, useEffect, useRef } from 'react';
import { Button, Modal, Form, Input, Select, Switch, message, Row, Col, Typography, Space, Divider, List, Tag, Popconfirm, FloatButton, Tooltip, Spin } from 'antd';
import { 
  PlayCircleOutlined, 
  PauseCircleOutlined, 
  StopOutlined, 
  SettingOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  TrophyOutlined,
  BarChartOutlined,
  HistoryOutlined
} from '@ant-design/icons';
import { focusService, motivationService, statisticsService } from '../services/api';
import { useAuth } from '../store/AuthContext';
import { useBackgroundTimer } from '../components/BackgroundTimerManager';
import TodayStatsModal from '../components/TodayStatsModal';

const { Title, Text } = Typography;
const { Option } = Select;

interface Timer {
  id: number;
  name: string;
  work_duration: number;
  break_duration: number;
  is_default: boolean;
}

interface FocusSettings {
  id: number;
  user_id: number;
  work_duration: number;
  short_break_duration: number;
  long_break_duration: number;
  long_break_interval: number;
  auto_start_breaks: boolean;
  auto_start_work: boolean;
  sound_enabled: boolean;
  desktop_notifications: boolean;
  motivation_type: string;
  created_at?: string;
  updated_at?: string;
  timers?: Timer[];
}

interface FocusSession {
  id: number;
  session_type: 'pomodoro' | 'break';
  duration: number;
  status: 'active' | 'completed' | 'paused' | 'cancelled';
  start_time: string;
  end_time?: string;
}

const FocusMode: React.FC = () => {
  const { user } = useAuth();
  const { 
    timerState, 
    startTimer: startBackgroundTimer, 
    pauseTimer: pauseBackgroundTimer, 
    resumeTimer: resumeBackgroundTimer, 
    stopTimer: stopBackgroundTimer, 
    updateTimer: updateBackgroundTimer,
    isBackgroundActive 
  } = useBackgroundTimer();
  
  const [settings, setSettings] = useState<FocusSettings | null>(null);
  const [currentTimer, setCurrentTimer] = useState<Timer | null>(null);
  const [currentSession, setCurrentSession] = useState<FocusSession | null>(null);
  const [timeLeft, setTimeLeft] = useState(0);
  const [isRunning, setIsRunning] = useState(false);
  const [isPaused, setIsPaused] = useState(false);
  const [isRestarting, setIsRestarting] = useState(false);
  const [isTimerCompleted, setIsTimerCompleted] = useState(false);
  const notificationSentRef = useRef(false);
  const handleTimerCompleteRef = useRef(false);
  const [isWorkSession, setIsWorkSession] = useState(true);
  const [settingsVisible, setSettingsVisible] = useState(false);
  const [timerFormVisible, setTimerFormVisible] = useState(false);
  const [editingTimer, setEditingTimer] = useState<Timer | null>(null);
  const [sessions, setSessions] = useState<FocusSession[]>([]);
  const [todayPoints, setTodayPoints] = useState(0);
  const [statsVisible, setStatsVisible] = useState(false);
  const [historyVisible, setHistoryVisible] = useState(false);
  const [isInitialized, setIsInitialized] = useState(false);
  const [cacheRestored, setCacheRestored] = useState(false);
  const [timerReady, setTimerReady] = useState(false);
  const [pageReady, setPageReady] = useState(false);
  const [showMotivation, setShowMotivation] = useState(false);
  const [motivationContent, setMotivationContent] = useState('');
  const [motivationWords, setMotivationWords] = useState<string[]>([]);
  const [motivationEmojis, setMotivationEmojis] = useState<string[]>([]);

  // 加载激励内容
  const loadMotivationContent = async () => {
    try {
      const [textResponse, emojiResponse] = await Promise.all([
        motivationService.getContent('text'),
        motivationService.getContent('emoji')
      ]);
      
      if ((textResponse as any).success) {
        setMotivationWords((textResponse as any).data.map((item: any) => item.content));
      }
      
      if ((emojiResponse as any).success) {
        setMotivationEmojis((emojiResponse as any).data.map((item: any) => item.content));
      }
    } catch (error) {
      console.error('加载激励内容失败:', error);
      // 使用默认内容作为后备
      setMotivationWords([
        '太棒了！你完成了一个专注时段！',
        '继续保持，你做得很好！',
        '专注力在提升，加油！',
        '每一次专注都是进步！',
        '你已经很棒了！',
        '专注让你更强大！',
        '坚持下去，你会成功的！',
        '专注是成功的关键！'
      ]);
      setMotivationEmojis(['🎉', '👏', '💪', '🔥', '⭐', '🌟', '💯', '🎯', '🏆', '✨']);
    }
  };

  // 显示激励内容
  const showMotivationContent = () => {
    if (!settings?.motivation_type || settings.motivation_type === 'none') {
      return;
    }

    let content = '';
    let duration = 3000; // 默认3秒

    if (settings.motivation_type === 'words') {
      content = motivationWords[Math.floor(Math.random() * motivationWords.length)];
      duration = 3000; // 言语显示3秒
    } else if (settings.motivation_type === 'emoji') {
      content = motivationEmojis[Math.floor(Math.random() * motivationEmojis.length)];
      duration = 1000; // 表情显示1秒
    } else if (settings.motivation_type === 'random') {
      const isWords = Math.random() < 0.5;
      if (isWords) {
        content = motivationWords[Math.floor(Math.random() * motivationWords.length)];
        duration = 3000;
      } else {
        content = motivationEmojis[Math.floor(Math.random() * motivationEmojis.length)];
        duration = 1000;
      }
    }

    if (content) {
      // 显示激励内容
      setMotivationContent(content);
      setShowMotivation(true);
      
      // 设置自动隐藏
      setTimeout(() => {
        setShowMotivation(false);
        setMotivationContent('');
      }, duration);
    }
  };
  
  const intervalRef = useRef<NodeJS.Timeout | null>(null);
  const currentTimerRef = useRef<Timer | null>(null);

  // 同步后台计时器状态
  useEffect(() => {
    setTimeLeft(timerState.timeLeft);
    setIsRunning(timerState.isRunning);
    setIsPaused(timerState.isPaused);
    if (timerState.currentTimer) {
      setCurrentTimer(timerState.currentTimer);
    }
  }, [timerState]);
  const [settingsForm] = Form.useForm();
  const [timerForm] = Form.useForm();

  // 缓存键名
  const CACHE_KEY = `focus_state_${user?.id || 'default'}`;

  // 激励语句和表情
  const motivationTexts = [
    "加油！你正在变得更好！",
    "专注是成功的关键！",
    "每一分钟的努力都值得！",
    "坚持下去，胜利就在前方！",
    "你的专注力正在提升！",
    "学习让生活更精彩！",
    "每一次专注都是进步！",
    "你比昨天更优秀了！"
  ];


  // 保存状态到缓存
  const saveStateToCache = () => {
    const state = {
      currentTimer,
      currentSession,
      timeLeft,
      isRunning,
      isWorkSession,
      todayPoints,
      timestamp: Date.now()
    };
    localStorage.setItem(CACHE_KEY, JSON.stringify(state));
  };

  // 从缓存恢复状态
  const restoreStateFromCache = () => {
    try {
      const cached = localStorage.getItem(CACHE_KEY);
      if (cached) {
        const state = JSON.parse(cached);
        // 检查缓存是否过期（超过1小时）
        if (Date.now() - state.timestamp < 60 * 60 * 1000) {
          // 恢复所有状态
          if (state.currentTimer) {
            setCurrentTimer(state.currentTimer);
          }
          if (state.currentSession) {
            setCurrentSession(state.currentSession);
          }
          setTimeLeft(state.timeLeft || 0);
          setIsRunning(false); // 不恢复运行状态，需要用户手动开始
          setIsWorkSession(state.isWorkSession !== undefined ? state.isWorkSession : true);
          setTodayPoints(state.todayPoints || 0);
        } else {
          // 缓存过期，清除缓存
          localStorage.removeItem(CACHE_KEY);
        }
      }
    } catch (error) {
      console.error('恢复缓存状态失败:', error);
      // 清除损坏的缓存
      localStorage.removeItem(CACHE_KEY);
    } finally {
      // 标记缓存恢复完成
      setCacheRestored(true);
    }
  };

  // 初始化页面
  useEffect(() => {
    if (!isInitialized) {
      // 先恢复缓存状态
      restoreStateFromCache();
      // 然后加载设置和会话数据
      const initializeData = async () => {
        await loadSettings();
        await loadSessions();
        await loadMotivationContent();
        
        // 自动请求通知权限
        if ('Notification' in window && Notification.permission === 'default') {
          console.log('请求通知权限...');
          Notification.requestPermission().then(permission => {
            console.log('通知权限请求结果:', permission);
            if (permission === 'granted') {
              message.success('桌面通知已启用！');
            } else if (permission === 'denied') {
              message.warning('桌面通知被拒绝，请在浏览器设置中手动开启');
            }
          });
        }
        
        // 添加短暂延迟确保所有数据加载完成
        await new Promise(resolve => setTimeout(resolve, 500));
        setPageReady(true);
      };
      initializeData();
      setIsInitialized(true);
    }
  }, [isInitialized]);

  // 当设置加载完成后，检查是否需要设置默认计时器
  useEffect(() => {
    if (settings && settings.timers && settings.timers.length > 0 && isInitialized && cacheRestored) {
      // 只有在初始化完成、缓存恢复完成后才设置默认计时器
      const currentTimerValue = currentTimerRef.current;
      if (!currentTimerValue) {
        // 如果当前没有计时器，优先选择默认计时器，如果没有则选择第一个
        const defaultTimer = settings.timers.find(t => t.is_default) || settings.timers[0];
        setCurrentTimer(defaultTimer);
        currentTimerRef.current = defaultTimer;
      } else {
        // 检查当前计时器是否仍然存在于设置列表中
        const timerExists = settings.timers.find(t => t.id === currentTimerValue.id);
        if (!timerExists) {
          // 当前计时器不在设置列表中，选择默认计时器或第一个
          const defaultTimer = settings.timers.find(t => t.is_default) || settings.timers[0];
          setCurrentTimer(defaultTimer);
          currentTimerRef.current = defaultTimer;
        }
        // 如果当前计时器存在，则保持不变
      }
      // 标记计时器已准备好
      setTimerReady(true);
    }
  }, [settings, isInitialized, cacheRestored]); // 移除currentTimer依赖，避免无限循环

  // 同步currentTimerRef
  useEffect(() => {
    currentTimerRef.current = currentTimer;
  }, [currentTimer]);

  // 状态变化时保存到缓存
  useEffect(() => {
    saveStateToCache();
  }, [currentTimer, currentSession, timeLeft, isRunning, isWorkSession, todayPoints]);

  // 监听计时器结束
  useEffect(() => {
    console.log('计时器状态检查:', { timeLeft, isRunning, isPaused, isTimerCompleted });
    if (timeLeft === 0 && !isTimerCompleted) {
      console.log('计时器结束，调用handleTimerComplete');
      setIsTimerCompleted(true); // 防止重复调用
      // 计时器结束，自动停止
      setIsRunning(false);
      setIsPaused(false);
      handleTimerComplete();
    }
  }, [timeLeft, isTimerCompleted]);

  // 清理定时器
  useEffect(() => {
    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, []);

  // 创建默认计时器
  const createDefaultTimer = async () => {
    try {
      console.log('开始创建默认计时器...');
      const response = await focusService.createTimer({
        name: '经典番茄',
        work_duration: 1500, // 25分钟 = 1500秒
        break_duration: 300, // 5分钟 = 300秒
        is_default: true
      });
      console.log('默认计时器创建成功:', response);
      // 重新加载设置
      await loadSettings();
    } catch (error: any) {
      console.error('创建默认计时器失败:', error);
      console.error('错误详情:', error.response?.data || error.message);
    }
  };

  const loadSettings = async () => {
    try {
      const response = await focusService.getSettings() as any;
      console.log('专注设置API响应:', response);
      console.log('设置数据类型检查:', {
        sound_enabled: response?.settings?.sound_enabled,
        sound_type: typeof response?.settings?.sound_enabled,
        desktop_notifications: response?.settings?.desktop_notifications,
        desktop_type: typeof response?.settings?.desktop_notifications
      });
      
      if (response && response.settings) {
        setSettings(response.settings);
        
        // 如果没有计时器，创建默认计时器
        console.log('检查计时器数量:', response.settings.timers?.length);
        console.log('计时器列表:', response.settings.timers);
        if (response.settings.timers && response.settings.timers.length === 0) {
          console.log('没有计时器，开始创建默认计时器...');
          await createDefaultTimer();
        } else {
          console.log('已有计时器，跳过创建默认计时器');
          console.log('现有计时器:', response.settings.timers.map((t: any) => t.name));
        }
      } else {
        throw new Error('API响应格式异常');
      }
    } catch (error: any) {
      console.error('加载专注设置失败:', error);
      console.error('错误详情:', error.response?.data || error.message);
      
      // 如果是认证错误，显示登录提示
      if (error.response?.status === 401) {
        message.error('请先登录后再使用专注模式');
      } else {
        message.error('加载设置失败，使用默认设置');
        
        // 使用默认设置作为备用方案
        const defaultSettings: FocusSettings = {
          id: 0,
          user_id: 0,
          work_duration: 1500, // 25分钟 = 1500秒
          short_break_duration: 300, // 5分钟 = 300秒
          long_break_duration: 900, // 15分钟 = 900秒
          long_break_interval: 4,
          auto_start_breaks: false,
          auto_start_work: false,
          sound_enabled: true,
          desktop_notifications: true,
          motivation_type: 'none',
          timers: [
            {
              id: 1,
              name: '经典番茄',
              work_duration: 1500, // 25分钟 = 1500秒
              break_duration: 300, // 5分钟 = 300秒
              is_default: true
            }
          ]
        };
        setSettings(defaultSettings);
      }
    }
  };

  const loadSessions = async () => {
    try {
      const response = await focusService.getSessions() as any;
      console.log('专注会话API响应:', response);
      
      if (response && response.sessions) {
        setSessions(response.sessions);
      } else {
        throw new Error('API响应格式异常');
      }
    } catch (error: any) {
      console.error('加载专注会话失败:', error);
      console.error('错误详情:', error.response?.data || error.message);
      
      // 如果是认证错误，显示登录提示
      if (error.response?.status === 401) {
        message.error('请先登录后再使用专注模式');
      } else {
        message.error('加载会话历史失败，使用空列表');
        setSessions([]);
      }
    }
  };

  const startTimer = async () => {
    if (!currentTimer) return;

    try {
      const sessionType = isWorkSession ? 'pomodoro' : 'break';
      const duration = isWorkSession ? currentTimer.work_duration : currentTimer.break_duration;
      
      const response = await focusService.startSession({
        timer_id: currentTimer.id,
        session_type: sessionType
      }) as any;

      setCurrentSession({
        id: response.sessionId,
        session_type: sessionType,
        duration: duration,
        status: 'active',
        start_time: new Date().toISOString()
      });

      setTimeLeft(duration); // duration已经是秒
      setIsRunning(true);
      setIsTimerCompleted(false); // 重置完成状态
      notificationSentRef.current = false; // 重置通知标记
      handleTimerCompleteRef.current = false; // 重置完成处理标记

      // 使用后台计时器
      startBackgroundTimer(currentTimer, isWorkSession);

      message.success(`${isWorkSession ? '工作' : '休息'}时间开始！`);
    } catch (error) {
      message.error('开始计时失败');
    }
  };

  const pauseTimer = () => {
    pauseBackgroundTimer(); // 使用后台计时器的暂停功能
  };

  const resumeTimer = () => {
    resumeBackgroundTimer(); // 使用后台计时器的恢复功能
  };

  const stopTimer = () => {
    setIsRunning(false);
    setIsPaused(false);
    setTimeLeft(0);
    setCurrentSession(null);
    setIsTimerCompleted(false); // 重置完成状态
    notificationSentRef.current = false; // 重置通知标记
    handleTimerCompleteRef.current = false; // 重置完成处理标记
    stopBackgroundTimer(); // 使用后台计时器的停止功能
    message.info('计时已停止');
  };

  const handleTimerComplete = async () => {
    // 防止重复调用
    if (handleTimerCompleteRef.current) {
      console.log('handleTimerComplete已被调用，跳过重复执行');
      return;
    }
    handleTimerCompleteRef.current = true;
    console.log('开始执行handleTimerComplete');
    
    try {
      if (currentSession) {
        // 完成当前会话
        await focusService.completeSession(currentSession.id);
        message.success(`${isWorkSession ? '工作' : '休息'}时间完成！`);
        
        // 播放提示音（如果启用）
        console.log('声音设置:', settings?.sound_enabled, '类型:', typeof settings?.sound_enabled);
        if (settings?.sound_enabled) {
          console.log('尝试播放声音...');
          try {
            // 使用Web Audio API创建简单的提示音
            const audioContext = new (window.AudioContext || (window as any).webkitAudioContext)();
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();
            
            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);
            
            oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
            oscillator.frequency.setValueAtTime(600, audioContext.currentTime + 0.1);
            oscillator.frequency.setValueAtTime(800, audioContext.currentTime + 0.2);
            
            gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.5);
            
            oscillator.start(audioContext.currentTime);
            oscillator.stop(audioContext.currentTime + 0.5);
            
            console.log('声音播放成功');
          } catch (e) {
            console.log('声音播放失败:', e);
            // 备用方案：使用系统提示音
            try {
              const audio = new Audio();
              audio.src = 'data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgodDbq2EcBj+a2/LDciUFLIHO8tiJNwgZaLvt559NEAxQp+PwtmMcBjiR1/LMeSwFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBSuBzvLZiTYIG2m98OScTgwOUarm7blmGgU7k9n1unEiBS13yO+eizEIHWq+8+OWT';
              audio.play().catch(() => {
                console.log('备用声音播放也失败');
              });
            } catch (fallbackError) {
              console.log('备用声音播放失败:', fallbackError);
            }
          }
        } else {
          console.log('声音提醒已禁用');
        }
        
        // 发送桌面通知（如果启用）
        console.log('桌面通知设置:', settings?.desktop_notifications, '类型:', typeof settings?.desktop_notifications);
        console.log('通知权限:', Notification.permission);
        console.log('通知已发送:', notificationSentRef.current);
        
        if (!notificationSentRef.current && settings?.desktop_notifications && 'Notification' in window) {
          notificationSentRef.current = true; // 标记已发送
          
          if (Notification.permission === 'granted') {
            console.log('发送桌面通知...');
            new Notification('专注时间结束！', {
              body: '恭喜你完成了一个专注时段！',
              icon: '/favicon.ico'
            });
          } else if (Notification.permission === 'denied') {
            console.log('通知权限被拒绝，显示页面内通知');
            // 当权限被拒绝时，显示页面内通知
            message.info('专注时间结束！请允许浏览器通知以获得更好的体验。');
          } else {
            console.log('请求通知权限...');
            Notification.requestPermission().then(permission => {
              console.log('权限请求结果:', permission);
              if (permission === 'granted') {
                new Notification('专注时间结束！', {
                  body: '恭喜你完成了一个专注时段！',
                  icon: '/favicon.ico'
                });
              } else {
                console.log('用户拒绝了通知权限');
                message.info('专注时间结束！请允许浏览器通知以获得更好的体验。');
              }
            });
          }
        } else {
          console.log('桌面通知已禁用或不支持或已发送');
        }
        
        // 更新统计数据
        if (isWorkSession) {
          const duration = currentTimer?.work_duration || 0;
          const pointsPerSession = 10; // 每次专注固定10积分
          
          // 更新后端统计，让后端处理积分限制
          try {
            const response = await statisticsService.updateStats('focus_session', 1, duration, pointsPerSession);
            
            // 重新加载今日统计以获取最新数据
            const statsResponse = await statisticsService.getTodayStats();
            if (statsResponse.data?.success) {
              const newTodayPoints = statsResponse.data.data.today.points_earned || 0;
              setTodayPoints(newTodayPoints);
              
              // 根据积分变化判断是否获得积分
              const currentSessions = Math.floor(newTodayPoints / 10);
              if (newTodayPoints > (todayPoints || 0)) {
                message.success(`专注完成！获得${pointsPerSession}积分！(${currentSessions}/5次)`);
              } else {
                message.info('今日专注次数已达到上限（5次），继续专注吧！');
              }
            }
          } catch (error) {
            console.error('更新统计数据失败:', error);
          }
        } else {
          // 休息会话
          const duration = currentTimer?.break_duration || 0;
          try {
            await statisticsService.updateStats('break_session', 1, duration, 0);
          } catch (error) {
            console.error('更新统计数据失败:', error);
          }
        }
        
        // 显示激励内容（仅在非自动开始模式下）
        if (!settings?.auto_start_work && !settings?.auto_start_breaks) {
          showMotivationContent();
        }
        
        // 切换会话类型
        setIsWorkSession(!isWorkSession);
        
        // 清除当前会话
        setCurrentSession(null);
        
        // 如果开启自动开始，自动开始下一个阶段
        if (settings?.auto_start_work && isWorkSession) {
          setTimeout(() => {
            startTimer();
          }, 1000);
        } else if (settings?.auto_start_breaks && !isWorkSession) {
          setTimeout(() => {
            startTimer();
          }, 1000);
        }
      }
    } catch (error) {
      console.error('完成会话失败:', error);
      message.error('完成会话失败');
    }
  };

  const completeSession = async () => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    }

    if (currentSession) {
      try {
        await focusService.completeSession(currentSession.id);
        
        if (isWorkSession) {
          setTodayPoints(prev => prev + 10);
          message.success('工作完成！获得10积分！');
          
          // 显示激励信息（简化版本，因为新数据库结构没有motivation_mode字段）
          const randomText = motivationTexts[Math.floor(Math.random() * motivationTexts.length)];
          message.info(randomText);
          
          const randomEmoji = motivationEmojis[Math.floor(Math.random() * motivationEmojis.length)];
          message.info(randomEmoji);
        } else {
          message.success('休息完成！');
        }

        // 切换到下一个阶段
        setIsWorkSession(!isWorkSession);
        setCurrentSession(null);
        setIsRunning(false);
        setTimeLeft(0);

        // 如果开启自动开始，自动开始下一个阶段
        if (settings?.auto_start_work && isWorkSession) {
          setTimeout(() => {
            startTimer();
          }, 2000);
        } else if (settings?.auto_start_breaks && !isWorkSession) {
          setTimeout(() => {
            startTimer();
          }, 2000);
        }

        loadSessions();
      } catch (error) {
        message.error('完成会话失败');
      }
    }
  };

  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  const updateSettings = async (values: any) => {
    try {
      await focusService.updateSettings(values);
      // 重新加载设置以获取最新的计时器数据
      await loadSettings();
      
      // 如果当前有选中的计时器，更新为最新的数据
      if (currentTimer && settings?.timers) {
        const updatedTimer = settings.timers.find(timer => timer.id === currentTimer.id);
        if (updatedTimer) {
          setCurrentTimer(updatedTimer);
          // 同时更新缓存中的计时器数据
          currentTimerRef.current = updatedTimer;
        }
      }
      
      setSettingsVisible(false);
      message.success('设置更新成功');
    } catch (error) {
      message.error('更新设置失败');
    }
  };

  const createTimer = async (values: any) => {
    try {
      await focusService.createTimer(values);
      setTimerFormVisible(false);
      timerForm.resetFields();
      loadSettings();
      message.success('计时器创建成功');
    } catch (error) {
      message.error('创建计时器失败');
    }
  };

  const updateTimerSettings = async (values: any) => {
    if (!editingTimer) return;
    
    try {
      await focusService.updateTimer(editingTimer.id, values);
      setTimerFormVisible(false);
      setEditingTimer(null);
      timerForm.resetFields();
      loadSettings();
      message.success('计时器更新成功');
    } catch (error) {
      message.error('更新计时器失败');
    }
  };

  const deleteTimer = async (timerId: number) => {
    try {
      await focusService.deleteTimer(timerId);
      loadSettings();
      message.success('计时器删除成功');
    } catch (error) {
      message.error('删除计时器失败');
    }
  };

  const openTimerForm = (timer?: Timer) => {
    if (timer) {
      setEditingTimer(timer);
      timerForm.setFieldsValue(timer);
    } else {
      setEditingTimer(null);
      timerForm.resetFields();
    }
    setTimerFormVisible(true);
  };

  const getProgressPercentage = () => {
    if (!currentSession || !currentTimer || timeLeft === 0) return 0;
    const totalSeconds = isWorkSession ? currentTimer.work_duration : currentTimer.break_duration;
    if (totalSeconds === 0) return 0;
    return ((totalSeconds - timeLeft) / totalSeconds) * 100;
  };

  // 格式化时间显示
  const formatDuration = (seconds: number) => {
    if (seconds < 60) {
      return `${seconds}秒`;
    } else {
      const minutes = Math.floor(seconds / 60);
      const remainingSeconds = seconds % 60;
      if (remainingSeconds === 0) {
        return `${minutes}分钟`;
      } else {
        return `${minutes}分${remainingSeconds}秒`;
      }
    }
  };

  // 如果页面未准备好，显示加载状态
  if (!pageReady) {
    return (
      <div style={{
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        height: 'calc(100vh - 160px)',
        background: 'white',
        color: '#2c3e50',
        margin: '-24px -16px'
      }}>
        <Spin size="large" />
        <div style={{ marginTop: '20px', fontSize: '16px' }}>
          正在加载专注模式...
        </div>
      </div>
    );
  }

  return (
    <>
      <style>
        {`
          @keyframes fadeInScale {
            0% {
              opacity: 0;
              transform: scale(0.8);
            }
            100% {
              opacity: 1;
              transform: scale(1);
            }
          }
          
          @keyframes fadeOutScale {
            0% {
              opacity: 1;
              transform: scale(1);
            }
            100% {
              opacity: 0;
              transform: scale(0.8);
            }
          }
          
          @keyframes breathe {
            0%, 100% {
              transform: scale(1);
              box-shadow: 0 4px 20px rgba(0,0,0,0.1);
            }
            50% {
              transform: scale(1.02);
              box-shadow: 0 8px 30px rgba(0,0,0,0.15);
            }
          }
        `}
      </style>
      <div style={{ 
        height: 'calc(100vh - 160px)', // 减去Layout的margin(48px) + padding(48px) + header(64px)
        background: 'white',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '20px',
        overflow: 'hidden',
      position: 'relative',
      boxSizing: 'border-box',
      margin: '-24px -16px' // 抵消Layout的margin
    }}>
      {/* 主计时器区域 - 居中显示 */}
      <div style={{ 
        display: 'flex', 
        flexDirection: 'column', 
        alignItems: 'center',
        maxWidth: '600px',
        width: '100%'
      }}>
        {/* 当前计时器选择 */}
        <div style={{ marginBottom: '30px', textAlign: 'center' }}>
          <Title level={4} style={{ marginBottom: '10px', color: '#2c3e50' }}>
            当前计时器
          </Title>
          {timerReady && pageReady ? (
            <Select
              value={currentTimer?.id}
              onChange={(value) => {
                const timer = settings?.timers?.find(t => t.id === value);
                setCurrentTimer(timer || null);
              }}
              style={{ width: '200px' }}
              size="large"
              disabled={isRunning || isPaused}
            >
              {settings?.timers?.map(timer => (
                <Option key={timer.id} value={timer.id}>
                  {timer.name?.replace(/[0\s]+$/, '').trim() || timer.name} ({formatDuration(timer.work_duration)}/{formatDuration(timer.break_duration)})
                </Option>
              ))}
            </Select>
          ) : (
            <div style={{ 
              width: '200px', 
              height: '40px', 
              display: 'flex', 
              alignItems: 'center', 
              justifyContent: 'center',
              border: '1px solid #d9d9d9',
              borderRadius: '6px',
              background: '#fafafa',
              margin: '0 auto'
            }}>
              <Spin size="small" />
            </div>
          )}
        </div>

        {/* 阶段指示器 */}
        <div style={{ marginBottom: '30px' }}>
          <Tag 
            color={isWorkSession ? '#1890ff' : '#52c41a'} 
            style={{ fontSize: '16px', padding: '8px 16px' }}
          >
            {isWorkSession ? '🍅 工作时间' : '☕ 休息时间'}
          </Tag>
        </div>

        {/* 圆形进度条 */}
        <div style={{ position: 'relative', marginBottom: '40px' }}>
          {showMotivation ? (
            /* 激励模式：长方形显示 */
            <div
              style={{
                width: '600px',  // 圆形进度条直径(300px)的两倍
                height: '300px', // 圆形进度条的直径
                background: 'white',
                borderRadius: '12px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                boxShadow: '0 8px 32px rgba(0,0,0,0.15)',
                animation: 'fadeInScale 0.3s ease-out',
                margin: '0 auto'
              }}
            >
              <Text 
                style={{ 
                  fontSize: motivationContent.length > 10 ? '28px' : '56px', 
                  fontWeight: 'bold', 
                  color: '#1890ff',
                  textAlign: 'center',
                  textShadow: '0 2px 4px rgba(0,0,0,0.1)',
                  lineHeight: 1.2
                }}
              >
                {motivationContent}
              </Text>
            </div>
          ) : (
            /* 正常模式：圆形进度条 */
            <div
              style={{
                width: '300px',
                height: '300px',
                borderRadius: '50%',
                background: `conic-gradient(${isWorkSession ? '#1890ff' : '#52c41a'} 0deg ${getProgressPercentage() * 3.6}deg, #f0f0f0 ${getProgressPercentage() * 3.6}deg 360deg)`,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                position: 'relative',
                transition: 'all 0.3s ease-in-out',
                boxShadow: '0 4px 20px rgba(0,0,0,0.1)',
                animation: isRunning ? 'breathe 2s ease-in-out infinite' : 'none',
                margin: '0 auto'
              }}
            >
              <div
                style={{
                  width: '240px',
                  height: '240px',
                  borderRadius: '50%',
                  background: 'white',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  flexDirection: 'column',
                  boxShadow: '0 4px 20px rgba(0,0,0,0.1)',
                  position: 'relative'
                }}
              >
                <Text style={{ fontSize: '48px', fontWeight: 'bold', color: '#2c3e50' }}>
                  {formatTime(timeLeft)}
                </Text>
                <Text style={{ fontSize: '16px', color: '#7f8c8d' }}>
                  {currentTimer ? formatDuration(isWorkSession ? currentTimer.work_duration : currentTimer.break_duration) : ''}
                </Text>
              </div>
            </div>
          )}
        </div>

        {/* 控制按钮 */}
        <div style={{ 
          display: 'flex', 
          gap: '20px', 
          justifyContent: 'center',
          alignItems: 'center',
          minHeight: '60px' // 防止高度变化
        }}>
          {/* 重新开始加载状态 */}
          {isRestarting && (
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: '10px',
                padding: '0 30px',
                height: '50px',
                fontSize: '16px',
                color: '#1890ff'
              }}
            >
              <Spin size="small" />
              重新开始中...
            </div>
          )}
          
          {/* 倒计时未开始时，只显示开始按钮 */}
          {!isRunning && timeLeft === 0 && !isRestarting && (
            <div
              style={{
                animation: 'fadeInScale 0.3s ease-out',
                display: 'inline-block'
              }}
            >
              <Button
                type="primary"
                size="large"
                icon={<PlayCircleOutlined />}
                onClick={startTimer}
                style={{
                  height: '50px',
                  padding: '0 30px',
                  fontSize: '16px',
                  borderRadius: '25px',
                  transition: 'all 0.2s ease'
                }}
              >
                开始
              </Button>
            </div>
          )}
          
          {/* 运行或暂停时显示：暂停/继续、结束、重新开始 */}
          {((isRunning || isPaused) && timeLeft > 0) && !isRestarting && (() => {
            console.log('Rendering timer buttons:', { isRunning, isPaused, isRestarting, timeLeft });
            return true;
          })() && (
            <div
              style={{
                animation: 'fadeInScale 0.3s ease-out',
                display: 'flex',
                gap: '20px',
                alignItems: 'center'
              }}
            >
              {/* 暂停/继续按钮 */}
              {isRunning ? (
                <Button
                  size="large"
                  icon={<PauseCircleOutlined />}
                  onClick={pauseTimer}
                  style={{
                    height: '50px',
                    padding: '0 30px',
                    fontSize: '16px',
                    borderRadius: '25px',
                    transition: 'all 0.2s ease'
                  }}
                >
                  暂停
                </Button>
              ) : (
                <Button
                  type="primary"
                  size="large"
                  icon={<PlayCircleOutlined />}
                  onClick={resumeTimer}
                  style={{
                    height: '50px',
                    padding: '0 30px',
                    fontSize: '16px',
                    borderRadius: '25px',
                    transition: 'all 0.2s ease'
                  }}
                >
                  继续
                </Button>
              )}
              
              {/* 结束按钮 */}
              <Button
                size="large"
                icon={<StopOutlined />}
                onClick={stopTimer}
                style={{
                  height: '50px',
                  padding: '0 30px',
                  fontSize: '16px',
                  borderRadius: '25px',
                  transition: 'all 0.2s ease'
                }}
              >
                结束
              </Button>
              
              {/* 重新开始按钮 */}
              <Button
                size="large"
                icon={<PlayCircleOutlined />}
                onClick={async () => {
                  setIsRestarting(true);
                  
                  // 直接重置状态并开始，避免中间状态
                  setIsRunning(false);
                  setIsPaused(false);
                  setTimeLeft(0);
                  setCurrentSession(null);
                  setIsTimerCompleted(false); // 重置完成状态
                  notificationSentRef.current = false; // 重置通知标记
                  handleTimerCompleteRef.current = false; // 重置完成处理标记
                  stopBackgroundTimer();
                  
                  // 立即开始新的计时器
                  setTimeout(async () => {
                    await startTimer();
                    setIsRestarting(false);
                  }, 50);
                }}
                style={{
                  height: '50px',
                  padding: '0 30px',
                  fontSize: '16px',
                  borderRadius: '25px',
                  transition: 'all 0.2s ease'
                }}
              >
                重新开始
              </Button>
            </div>
          )}
        </div>
      </div>

      {/* 右下角浮动按钮组 */}
      <FloatButton.Group
        trigger="hover"
        type="primary"
        style={{ right: 24, bottom: 24 }}
        icon={<BarChartOutlined />}
      >
        <Tooltip title="今日统计" placement="left">
          <FloatButton 
            icon={<TrophyOutlined />} 
            onClick={() => setStatsVisible(true)}
          />
        </Tooltip>
        <Tooltip title="最近会话" placement="left">
          <FloatButton 
            icon={<HistoryOutlined />} 
            onClick={() => setHistoryVisible(true)}
          />
        </Tooltip>
        <Tooltip title={isRunning || isPaused ? "计时器运行中，无法修改设置" : "专注设置"} placement="left">
          <FloatButton 
            icon={<SettingOutlined />} 
            onClick={() => {
              if (!isRunning && !isPaused) {
                setSettingsVisible(true);
              }
            }}
            style={{
              opacity: isRunning || isPaused ? 0.5 : 1,
              cursor: isRunning || isPaused ? 'not-allowed' : 'pointer'
            }}
          />
        </Tooltip>
      </FloatButton.Group>

      {/* 今日统计弹窗 */}
      <TodayStatsModal
        visible={statsVisible}
        onCancel={() => setStatsVisible(false)}
      />

      {/* 最近会话弹窗 */}
      <Modal
        title={
          <Space>
            <HistoryOutlined />
            最近会话
          </Space>
        }
        open={historyVisible}
        onCancel={() => setHistoryVisible(false)}
        footer={null}
        width={500}
      >
        <List
          dataSource={sessions.slice(0, 10)}
          renderItem={(session) => (
            <List.Item>
              <List.Item.Meta
                title={
                  <Space>
                    <Tag color={session.session_type === 'pomodoro' ? 'green' : 'blue'}>
                      {session.session_type === 'pomodoro' ? '工作' : '休息'}
                    </Tag>
                    <Text>{formatDuration(session.duration)}</Text>
                    {session.status === 'completed' && <Tag color="success">已完成</Tag>}
                  </Space>
                }
                description={new Date(session.start_time).toLocaleString()}
              />
            </List.Item>
          )}
        />
        {sessions.length === 0 && (
          <div style={{ textAlign: 'center', padding: '40px 0', color: '#999' }}>
            暂无会话记录
          </div>
        )}
      </Modal>

      {/* 设置弹窗 */}
      <Modal
        title="专注设置"
        open={settingsVisible}
        closable={true}
        maskClosable={true}
        onCancel={() => {
          // 重置表单到原始状态，清除缓存
          settingsForm.resetFields();
          settingsForm.setFieldsValue(settings || {});
          // 直接关闭，不保存更改
          setSettingsVisible(false);
        }}
        footer={null}
        width={600}
      >
        <Form
          form={settingsForm}
          layout="vertical"
          onFinish={updateSettings}
          initialValues={settings || {}}
        >
          <Form.Item
            name="auto_start_work"
            label="自动开始工作"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="auto_start_breaks"
            label="自动开始休息"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="sound_enabled"
            label="声音提醒"
            valuePropName="checked"
            extra="计时器结束时播放提示音"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="desktop_notifications"
            label="桌面通知"
            valuePropName="checked"
            extra="计时器结束时显示桌面通知（需要浏览器权限）"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="motivation_type"
            label="激励方式"
            extra="计时器结束时显示的激励内容"
          >
            <Select placeholder="选择激励方式">
              <Option value="none">不激励</Option>
              <Option value="words">言语激励</Option>
              <Option value="emoji">表情激励</Option>
              <Option value="random">随机激励</Option>
            </Select>
          </Form.Item>
          
          {Notification.permission === 'denied' && (
            <div style={{ 
              padding: '12px', 
              backgroundColor: '#fff2e8', 
              border: '1px solid #ffb366', 
              borderRadius: '6px',
              marginBottom: '16px'
            }}>
              <div style={{ color: '#d46b08', marginBottom: '8px' }}>
                <strong>桌面通知被禁用</strong>
              </div>
              <div style={{ color: '#8c4a00', fontSize: '14px', marginBottom: '8px' }}>
                请在浏览器设置中手动开启通知权限：
              </div>
              <div style={{ color: '#8c4a00', fontSize: '12px' }}>
                • Chrome: 点击地址栏右侧的🔒图标 → 通知 → 允许<br/>
                • Safari: 偏好设置 → 网站 → 通知 → 允许<br/>
                • Firefox: 地址栏左侧的🔒图标 → 权限 → 通知 → 允许
              </div>
            </div>
          )}

          <Divider>计时器管理</Divider>

          <div style={{ marginBottom: '16px' }}>
            <Button
              type="dashed"
              icon={<PlusOutlined />}
              onClick={() => openTimerForm()}
              style={{ width: '100%' }}
            >
              添加计时器
            </Button>
          </div>

          <List
            dataSource={settings?.timers || []}
            renderItem={(timer) => {
              return (
                <List.Item
                  actions={[
                    <Button
                      type="text"
                      icon={<EditOutlined />}
                      onClick={() => openTimerForm(timer)}
                      disabled={timer.is_default}
                    />,
                    <Popconfirm
                      title="确定要删除这个计时器吗？"
                      onConfirm={() => deleteTimer(timer.id)}
                      disabled={timer.is_default}
                    >
                      <Button
                        type="text"
                        danger
                        icon={<DeleteOutlined />}
                        disabled={timer.is_default}
                      />
                    </Popconfirm>
                  ]}
                >
                  <List.Item.Meta
                    title={
                      <Space>
                        <span>{timer.name?.replace(/[0\s]+$/, '').trim() || timer.name}</span>
                        {Boolean(timer.is_default) && <Tag color="blue">默认</Tag>}
                      </Space>
                    }
                    description={`工作: ${formatDuration(timer.work_duration)}, 休息: ${formatDuration(timer.break_duration)}`}
                  />
                </List.Item>
              );
            }}
          />

          <Form.Item style={{ marginTop: '24px', marginBottom: 0 }}>
            <Button type="primary" htmlType="submit" block>
              保存设置
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 计时器表单弹窗 */}
      <Modal
        title={editingTimer ? '编辑计时器' : '添加计时器'}
        open={timerFormVisible}
        onCancel={() => {
          setTimerFormVisible(false);
          setEditingTimer(null);
          timerForm.resetFields();
        }}
        footer={null}
      >
        <Form
          form={timerForm}
          layout="vertical"
          onFinish={editingTimer ? updateTimerSettings : createTimer}
        >
          <Form.Item
            name="name"
            label="计时器名称"
            rules={[{ required: true, message: '请输入计时器名称' }]}
          >
            <Input placeholder="例如：经典番茄" />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="work_duration"
                label="工作时长（秒）"
                rules={[{ required: true, message: '请输入工作时长' }]}
              >
                <Input type="number" min={1} max={7200} placeholder="1500" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="break_duration"
                label="休息时长（秒）"
                rules={[{ required: true, message: '请输入休息时长' }]}
              >
                <Input type="number" min={0} max={3600} placeholder="300" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item style={{ marginBottom: 0 }}>
            <Button type="primary" htmlType="submit" block>
              {editingTimer ? '更新' : '创建'}
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
    </>
  );
};

export default FocusMode;
